import api from '../../api/api'
import Toast from '@vant/weapp/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    defaultAddress: {},
    showBottom: false,
    addressList: [],
    checked: false,
    order: [],
    totalNum: null,
    totalPrice: null,
    sids: [],
    timestamp: ''
  },
  async findAddress() {
    const res = await api.getAddressList({ tokenString: wx.getStorageSync('token') })
    console.log('地址列表', res);
    res.data.result.forEach((item, index) => {
      item.checked = false
      item.index = index
      // item.id = index + 1
      if (item.isDefault == 1) {
        // item.chosenAddressId = item.id
        this.setData({
          defaultAddress: item
        })
      }
    })
  },
  onChange(e) {
    let index = e.currentTarget.dataset.index
    let addressList = this.data.addressList
    let item = e.currentTarget.dataset.item
    addressList.forEach((item, i) => {
      if (i === index) {
        item.checked = true;
      } else {
        item.checked = false;
      }
    })
    this.setData({
      addressList: addressList,
      defaultAddress: item
    })
  },

  toAdd() {
    wx.navigateTo({
      url: '/pages/add-address/add-address',
    })
  },
  async getAddressListData() {
    let tokenString = wx.getStorageSync('token')
    const res = await api.getAddressList({ tokenString })
    if (res.data.code == 20000) {
      console.log('地址列表', res)
      this.setData({
        addressList: res.data.result
      })
    }
  },
  showPopup(e) {
    let id = this.data.defaultAddress.id
    let index = e.currentTarget.dataset.index
    let addressList = this.data.addressList
    addressList.forEach((item, i) => {
      if (item.id == id) {
        item.checked = true
      } else {
        item.checked = false
      }
    })
    this.setData({
      showBottom: true,
      addressList: addressList
    })
  },
  hidePopup() {
    this.setData({
      showBottom: false
    })
  },
  toDetail(e) {
    let aid = e.currentTarget.dataset.aid
    wx.navigateTo({
      url: '/pages/edit-address/edit-address?aid=' + aid,
    })
  },
  async orderPro(sids) {
    const res = await api.commitShopcart({ sids, tokenString: wx.getStorageSync('token') })
    console.log('确认订单', res)
    let totalNum = null
    let totalPrice = null
    res.data.result.forEach((v) => {
      totalNum += v.count
      totalPrice += v.count * v.price
    })
    this.setData({
      order: res.data.result,
      totalNum,
      totalPrice
    })
  },
  async pay() {
    let tokenString = wx.getStorageSync('token')
    const res = await api.pay({
      tokenString,
      sids: JSON.stringify(this.data.sids),
      phone: this.data.defaultAddress.tel,
      address: this.data.defaultAddress.province + this.data.defaultAddress.city + this.data.defaultAddress.county + this.data.defaultAddress.addressDetail,
      receiver: this.data.defaultAddress.name
    })
    if (res.data.code == 60000) {
      console.log('订单结算', res);
      Toast.success(res.data.msg)
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/my-orders/my-orders',
        })
      }, 1500)
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let sids = options.sids.split(',')
    let time = new Date(parseInt(options.timer));
    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let day = time.getDate()
    let hour = time.getHours()
    let minute = time.getMinutes()
    let second = time.getSeconds()
    let timestamp = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute) + ':' + (second < 10 ? '0' + second : second)
    this.setData({
      sids,
      timestamp
    })
    this.findAddress()
    this.orderPro(sids)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAddressListData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})